package finbudgettable.client.ui.grid.cell.links;

import java.util.Comparator;

import com.google.gwt.cell.client.Cell;

import finbudget.client.ui.table.LinksField;
import finbudget.client.ui.table.Record;
import finbudget.shared.process.events.StringPair;
import finbudgettable.client.ui.grid.CellGrid;
import finbudgettable.client.ui.grid.column.GridColumn;

public class LinksColumn extends GridColumn<StringPair>{

	private LinksField field;

	protected LinksColumn(Builder builder, LinksField field) {
		super(builder);
		this.field = field;
	}

	@Override
	protected boolean isValueChanged(Record record, StringPair value) {
		return false;
	}

	@Override
	public StringPair getValue(Record record) {
		if (record != null && field != null) {
			return new StringPair(record.getValueString(field.getFieldName()), record.getValueString(field.getFieldLink()));
		}
		return null;
	}

    public static class Builder extends GridColumn.Builder<LinksCell, StringPair> {

    	private LinksField field;

		protected Builder(CellGrid grid, final LinksField field, boolean hasTotals) {
			super(grid, field.captionGrid, hasTotals);
			this.field = field;
			this.setComparator(new Comparator<Record>() {

				@Override
				public int compare(Record o1, Record o2) {
					String value1 = o1 == null ? null : o1.getValueString(field.getFieldName());
					String value2 = o2 == null ? null : o2.getValueString(field.getFieldName());
			        if (value1 == null && value2 == null) {
			            return 0;
			        }
			        if (value1 == null) {
			            return -1; // null first
			        }
			        if (value2 == null) {
			            return 1;
			        }
			        return value1.compareTo(value2);
				}

			});
		}

		@Override
		protected LinksCell createCell() {
			return new LinksCell();
		}

		@Override
		protected GridColumn<StringPair> createColumn(Cell<StringPair> cell) {
			return new LinksColumn(this, field);
		}
    	
    }

    public static Builder builder(CellGrid grid, LinksField field, boolean hasTotals) {
    	return new Builder(grid, field, hasTotals);
    }

}
